#include "include/socket.h"

namespace unet {

bool Socket::Open() {
  if (sock_ != INVALIED_FD)
    return true;

  int32 ret = ::socket(doman_, type_, protocol_);
  if (ret == -1) {
    PLOG(WARNING) << "socket error";
    return -1;
  }

  OperateFlag(true, FD_CLOEXEC);

  return true;
}

void Socket::SetNonBlock() {
  OperateFlag(true, O_NONBLOCK);
}

void Socket::SetBlock() {
  OperateFlag(false, O_NONBLOCK);
}

void Socket::OperateFlag(bool is_set, uint32 flag) {
  int32 ret = ::fcntl(sock_, F_GETFL);
  if (is_set) {
    ret |= flag;
  } else {
    ret &= !flag;
  }
  ::fcntl(sock_, F_SETFL, ret);
}

}
